import com.intellij.facet.Facet;
import com.intellij.facet.FacetManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;

import java.util.ArrayList;
import java.util.List;

/**
 * User: LSDsl
 * Date: 28.03.12
 * Time: 11:05
 */
public class i18nHelper extends AnAction {


    public void actionPerformed(AnActionEvent event) {
        final Module module = event.getData(DataKeys.MODULE);
        final Project project = event.getData(DataKeys.PROJECT);

        XmlFile xmlFile = (XmlFile) event.getData(LangDataKeys.PSI_FILE);
        String filePath = "res/values/strings.xml";//.replace('/', File.separatorChar);
//        final VirtualFile projectFile = module.getModuleFile().getParent().findFileByRelativePath(filePath);

        VirtualFile projectFile;
        try {
            projectFile = module.getModuleFile().getParent().findChild("res").findChild("values").findChild("strings.xml");
        } catch (NullPointerException e) {
            Messages.showMessageDialog(project, "Cannot find " + filePath + " file", "Sorry", Messages.getInformationIcon());
            return;

        }

        final XmlFile settingsXmlFile = (XmlFile) PsiManager.getInstance(project).findFile(projectFile);

        final String prefix = xmlFile.getName().replace(".xml", "");
        int c = 0;

        final List<PsiElement> childrens = getAllChilds(xmlFile.getRootTag());

        StringBuilder stringBuilder = new StringBuilder();
        for (PsiElement child : childrens) {
            final XmlAttribute attribute = ((XmlTag) child).getAttribute("android:text");
            if (attribute != null) {
                final String value = attribute.getValue();
                if (!value.startsWith("@")) {
                    final XmlAttribute id = ((XmlTag) child).getAttribute("android:id");
                    String suffix;
                    if (id != null) {
                        suffix = id.getValue().replace("@+id/", "");
                    } else {
                        suffix = String.valueOf(c);
                        c++;
                    }

//
//                    final XmlTag xmlTag = XmlElementFactory.getInstance(project).createTagFromText("<string name=\"" + prefix + "_" + suffix + "\">" + value + "</string>");
//                    xmlTag.setName("string");
//                    xmlTag.setAttribute("name", prefix+"_"+suffix);
//                    xmlTag.getValue().setText(value);

                    final XmlTag rootTag = settingsXmlFile.getRootTag();
                    final XmlTag tag = rootTag.createChildTag("string", rootTag.getNamespace(), value, false);
                    tag.setAttribute("name", prefix + "_" + suffix);
//                    rootTag.addSubTag(tag, false);

                    final String newValue = "@string/" + prefix + "_" + suffix;
                    RunnableHelper.runWriteCommand(project, new Runnable() {
                        @Override
                        public void run() {
                            rootTag.addSubTag(tag, false);
                            attribute.setValue(newValue);
                        }
                    });
//                    attribute.setValue("@string/" + prefix + "_" + suffix);
//                    settingsXmlFile.getRootTag().addSubTag(xmlTag, false);
                    stringBuilder.append("@string/" + prefix + "_" + suffix + "=" + value + "\n");
                }

            }

        }

        Messages.showMessageDialog(project, stringBuilder.length() > 0 ? stringBuilder.toString() : "Not found any text :(", "Result", Messages.getInformationIcon());
    }

    @Override
    public void update(AnActionEvent e) {
        final Module module = e.getData(DataKeys.MODULE);
        final Project project = e.getData(DataKeys.PROJECT);

        boolean visible = false;
        if (project != null && module != null) {
            final Facet[] facets = FacetManager.getInstance(module).getAllFacets();
            for (Facet facet : facets) {
                if (facet.getName().equalsIgnoreCase("android")) {
                    visible = e.getData(LangDataKeys.PSI_FILE) instanceof XmlFile;
                    break;
                }
            }
        }
        e.getPresentation().setVisible(visible);
        e.getPresentation().setEnabled(visible);
    }

    private List<PsiElement> getAllChilds(PsiElement root) {
        ArrayList<PsiElement> arrayList = new ArrayList<PsiElement>();
        final PsiElement[] children = root.getChildren();
        for (PsiElement child : children) {
            if (child instanceof XmlTag) {
                arrayList.add(child);
                arrayList.addAll(getAllChilds(child));
            }
        }

        return arrayList;
    }
}
